package app.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import app.entity.IOTPBean;
import app.entity.IOTPBody;
import app.htby.utils.Code;
import app.htby.utils.IOTSUtils;
import app.htby.utils.IotpBodyUtils;
import app.htby.utils.SocketUtils;
import app.socket.client.CtrlConnClientRunnable;

public class TestWebController {
	
	public static void main(String[] args) {
		Date startDate = new Date();// 调用时间
		Date endDate = new Date(startDate.getTime() + SocketUtils.TIME_OUT);// 结束时间
		System.out.println(startDate);
		System.out.println(endDate);
		String agreement = "http://htby.com/1/2/3/4/5_2018-05-21 09:00:00_300000_5";
		String runnableId = IOTSUtils.getUUID();
		String[] str = agreement.substring(agreement.lastIndexOf("/")).split("_");
		
		int TIME_OUT = Integer.parseInt(str[2]);
		System.out.println(TIME_OUT);
		
		// 获取IOTPBean
		List<byte[]> byteList = WebController.getIOTPBean(agreement, runnableId);

		for (byte[] bs : byteList) {
			// 循环发送 socket发送
			CtrlConnClientRunnable r = new CtrlConnClientRunnable(runnableId, "localhost", 8888, bs);
			new Thread(r).start();
		}

		IOTSUtils.ctrlResultMap.put(runnableId, SocketUtils.WAITING_CODE);
		String resultMsg = "";
		int i = 0;
		while (true) {
			Object result = IOTSUtils.ctrlResultMap.get(runnableId);
			// 如果结果没有变化，则继续 查询等待。
			if (!SocketUtils.WAITING_CODE.equals(result)) {
				byte[] bytes = (byte[]) IOTSUtils.ctrlResultMap.get(runnableId);
				// 结果不是等待，则得到返回值，结束循环
				System.out.println("result:" + Arrays.toString(bytes));
				// 将结果 转换
				IotpBodyUtils ibu = new IotpBodyUtils();
				Code c = ibu.toIotpBean(bytes);
				System.out.println(c.toString());
				IOTPBean iotpBean = ibu.getIotpBean();
				IOTPBody body = iotpBean.getBody();
				System.out.println(body);
				//获得协议体
				List<String> list = body.getBodyList();
				resultMsg = list.toString();
				System.out.println("resultMsg:" + resultMsg);
				break;
			}

			try {
				System.out.println(i++);
				// 每 ctyle 秒遍历一次
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
